package com.huang.lochy;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dk.bleNfc.BleManager.BleManager;
import com.dk.bleNfc.BleManager.ScannerCallback;
import com.dk.bleNfc.BleNfcDeviceService;
import com.dk.bleNfc.DeviceManager.BleNfcDevice;
import com.dk.bleNfc.DeviceManager.ComByteManager;
import com.dk.bleNfc.DeviceManager.DeviceManager;
import com.dk.bleNfc.DeviceManager.DeviceManagerCallback;
import com.dk.bleNfc.Exception.CardNoResponseException;
import com.dk.bleNfc.Exception.DeviceNoResponseException;
import com.dk.bleNfc.Tool.StringTool;
import com.dk.bleNfc.card.CpuCard;
import com.dk.bleNfc.card.FeliCa;
import com.dk.bleNfc.card.Iso14443bCard;
import com.dk.bleNfc.card.Iso15693Card;
import com.dk.bleNfc.card.Mifare;
import com.dk.bleNfc.card.Ntag21x;
import com.dk.bleNfc.BleManager.*;

import java.io.UnsupportedEncodingException;


public class MainActivity extends Activity {
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    BleNfcDeviceService mBleNfcDeviceService;
    private BleNfcDevice bleNfcDevice;
    private Scanner mScanner;
    private Button searchButton = null;
    private EditText msgText = null;
    private ProgressDialog readWriteDialog = null;

    private EditText etHr;
    private EditText etRr;
    private EditText etTemp;
    private EditText etSpO2;
    private EditText etPr;
    private EditText etPi;
    private EditText etSbp;
    private EditText etDbp;
    private EditText etMbp;
    private Button btnWismedWrite;
    private Button btnWismedRead;

    private StringBuffer msgBuffer;
    private BluetoothDevice mNearestBle = null;
    private int lastRssi = -100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        msgBuffer = new StringBuffer();

        searchButton = (Button)findViewById(R.id.searchButton);
        Button sendButton = (Button) findViewById(R.id.sendButton);
        Button changeBleNameButton = (Button) findViewById(R.id.changeBleNameButton);
        msgText = (EditText)findViewById(R.id.msgText);
        Button clearButton = (Button) findViewById(R.id.clearButton);
        Button openBeepButton = (Button) findViewById(R.id.openBeepButton);
        Button closeBeepButton = (Button) findViewById(R.id.closeBeepButton);
        Button openAntiLostButton = (Button) findViewById(R.id.openAntiLostButton);
        Button closeAntiLostButton = (Button) findViewById(R.id.closeAntiLostButton);
        Button openAutoSearchCard = (Button)findViewById(R.id.openAutoSearchCard);
        Button closeAutoSearchCard = (Button)findViewById(R.id.closeAutoSearchCard);
        btnWismedWrite = findViewById(R.id.btnWismedWrite);
        btnWismedRead = findViewById(R.id.btnWismedRead);
        etHr = findViewById(R.id.etHr);
        etRr = findViewById(R.id.etRr);
        etTemp = findViewById(R.id.etTemp);
        etSpO2 = findViewById(R.id.etSpO2);
        etPr = findViewById(R.id.etPr);
        etPi = findViewById(R.id.etPi);
        etSbp = findViewById(R.id.etSbp);
        etDbp = findViewById(R.id.etDbp);
        etMbp = findViewById(R.id.etMbp);
        readWriteDialog = new ProgressDialog(MainActivity.this);
        readWriteDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 标题
        readWriteDialog.setTitle("请稍等");
        // 设置ProgressDialog 提示信息
        readWriteDialog.setMessage("正在读写数据……");
        // 设置ProgressDialog 标题图标
        readWriteDialog.setIcon(R.drawable.ic_launcher);

        clearButton.setOnClickListener(new claerButtonListener());
        searchButton.setOnClickListener(new StartSearchButtonListener());
        sendButton.setOnClickListener(new SendButtonListener());
        changeBleNameButton.setOnClickListener(new changeBleNameButtonListener());
        openBeepButton.setOnClickListener(new OpenBeepButtonListener());
        closeBeepButton.setOnClickListener(new closeBeepButtonListener());
        openAntiLostButton.setOnClickListener(new OpenAntiLostButtonListener());
        closeAntiLostButton.setOnClickListener(new CloseAntiLostButtonListener());
        openAutoSearchCard.setOnClickListener(new OpenAutoSearchCardButtonListener());
        closeAutoSearchCard.setOnClickListener(new CloseAutoSearchCardButtonListener());
        btnWismedWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeOrReadMIData2(0);
            }
        });
        btnWismedRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeOrReadMIData2(1);
            }
        });

        if ( !gpsIsOPen(MainActivity.this) ) {
            System.out.println("log:" + "GPS未打开！");

            final AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(MainActivity.this);
            normalDialog.setTitle("请打开GPS");
            normalDialog.setMessage("搜索蓝牙需要打开GPS");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //...To-do
                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
                        }
                    });
            normalDialog.setNegativeButton("关闭",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //...To-do
                        }
                    });
            // 显示
            normalDialog.show();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //未拥有权限，提示用户允许app使用定位权限
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
            else {  //已经拥有权限
                //ble_nfc服务初始化
                Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
                bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
            }
        }
        else {    //API 23以下的，不需要动态申请权限
            //ble_nfc服务初始化
            Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
            bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        }

        //ble_nfc服务初始化
        Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        msgText.setText("BLE_NFC Demo v2.2.0 20180621");
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean gpsIsOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  //申请权限成功
                    // TODO request success
                    //ble_nfc服务初始化
                    Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
                    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
                }
                break;
        }
    }

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            BleNfcDeviceService mBleNfcDeviceService = ((BleNfcDeviceService.LocalBinder) service).getService();
            bleNfcDevice = mBleNfcDeviceService.bleNfcDevice;
            mScanner = mBleNfcDeviceService.scanner;
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
            mBleNfcDeviceService.setScannerCallback(scannerCallback);

            //开始搜索设备
            mScanner.startScan();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleNfcDeviceService = null;
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (mBleNfcDeviceService != null) {
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (readWriteDialog != null) {
            readWriteDialog.dismiss();
        }

        unbindService(mServiceConnection);
    }

    //Scanner 回调
    private ScannerCallback scannerCallback = new ScannerCallback() {
        @Override
        public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
            super.onReceiveScanDevice(device, rssi, scanRecord);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //StringTool.byteHexToSting(scanRecord.getBytes())
                System.out.println("Activity搜到设备：" + device.getName()
                        + " 信号强度：" + rssi
                        + " scanRecord：" + StringTool.byteHexToSting(scanRecord));
            }

            //搜索蓝牙设备并记录信号强度最强的设备
            if ( (scanRecord != null) && (device.getName() != null) && (StringTool.byteHexToSting(scanRecord).contains("017f5450") || device.getName().contains("HZ-") )) {  //从广播数据中过滤掉其它蓝牙设备
                //信号强度过滤，调整这个数值可以控制连接设备的范围
                if (rssi < -65) {
                    return;
                }

                //已经连接了设备，退出
                if ( bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED ) {
                    return;
                }

                mNearestBle = device;
                lastRssi = rssi;

                mScanner.stopScan();
                bleNfcDevice.requestConnectBleDevice(device.getAddress());
            }
        }

        @Override
        public void onScanDeviceStopped() {
            super.onScanDeviceStopped();
        }
    };

    //设备操作类回调
    private DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectBtDevice(boolean blnIsConnectSuc) {
            super.onReceiveConnectBtDevice(blnIsConnectSuc);
            if (blnIsConnectSuc) {
                System.out.println("Activity设备连接成功");
                msgBuffer.delete(0, msgBuffer.length());
                msgBuffer.append("设备连接成功!\r\n");
                if (mNearestBle != null) {
                    msgBuffer.append("设备名称：").append(bleNfcDevice.getDeviceName()).append("\r\n");
                }
                msgBuffer.append("信号强度：").append(lastRssi).append("dB\r\n");
                msgBuffer.append("SDK版本：" + BleNfcDevice.SDK_VERSIONS + "\r\n");
                handler.sendEmptyMessage(0);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //连接上后延时500ms后再开始发指令
                        try {
                            Thread.sleep(500L);
                            handler.sendEmptyMessage(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        //设备配置和设备信息读取
                        try {
                            /*获取设备版本号*/
                            byte versions = bleNfcDevice.getDeviceVersions();
                            msgBuffer.append("设备版本:").append(String.format("%02x", versions)).append("\r\n");
                            handler.sendEmptyMessage(0);

                            /*获取设备电池电压*/
                            double voltage = bleNfcDevice.getDeviceBatteryVoltage();
                            msgBuffer.append("设备电池电压:").append(String.format("%.2f", voltage)).append("\r\n");
                            if (voltage < 3.61) {
                                msgBuffer.append("设备电池电量低，请及时充电！");
                            } else {
                                msgBuffer.append("设备电池电量充足！");
                            }
                            handler.sendEmptyMessage(0);

                            /*设置快速传输参数*/
                            boolean isSuc = bleNfcDevice.androidFastParams(true);
                            if (isSuc) {
                                msgBuffer.append("\r\n蓝牙快速传输参数设置成功!");
                            }
                            else {
                                msgBuffer.append("\n不支持快速传输参数设置!");
                            }
                            handler.sendEmptyMessage(0);

                            /*修改设备序列号*/
//                                msgBuffer.append("\n修改设备序列号为：00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF");
//                                handler.sendEmptyMessage(0);
//                                byte[] newSerialNumberBytes = new byte[] {
//                                        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff,
//                                        0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte)0x88, (byte)0x99, (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff
//                                };
//                                isSuc = bleNfcDevice.changeSerialNumber(newSerialNumberBytes);
//                                if (isSuc) {
//                                    msgBuffer.append("\r\n设备序列号修改成功!");
//                                }
//                                else {
//                                    msgBuffer.append("\r\n设备序列号修改失败!");
//                                }
//                                handler.sendEmptyMessage(0);

                            /*获取设备序列号*/
                            try {
                                msgBuffer.append("\r\n开始获取设备序列号...\r\n");
                                handler.sendEmptyMessage(0);
                                byte[] serialNumberBytes = bleNfcDevice.getSerialNumber();
                                msgBuffer.append("设备序列号为：").append(StringTool.byteHexToSting(serialNumberBytes));
                            }catch (DeviceNoResponseException e) {
                                e.printStackTrace();
                            }

                            /*开启自动寻卡*/
                            msgBuffer.append("\n开启自动寻卡...\r\n");
                            handler.sendEmptyMessage(0);
                            //开始自动寻卡
                            startAutoSearchCard();
                        } catch (DeviceNoResponseException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }

        @Override
        public void onReceiveDisConnectDevice(boolean blnIsDisConnectDevice) {
            super.onReceiveDisConnectDevice(blnIsDisConnectDevice);
            System.out.println("Activity设备断开链接");
            msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("设备断开链接!");
            handler.sendEmptyMessage(0);
        }

        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            super.onReceiveConnectionStatus(blnIsConnection);
            System.out.println("Activity设备链接状态回调");
        }

        @Override
        public void onReceiveInitCiphy(boolean blnIsInitSuc) {
            super.onReceiveInitCiphy(blnIsInitSuc);
        }

        @Override
        public void onReceiveDeviceAuth(byte[] authData) {
            super.onReceiveDeviceAuth(authData);
        }

        @Override
        //寻到卡片回调
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                return;
            }

            System.out.println("Activity接收到激活卡片回调：UID->" + StringTool.byteHexToSting(bytCardSn) + " ATS->" + StringTool.byteHexToSting(bytCarATS));

            final int cardTypeTemp = cardType;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isReadWriteCardSuc = false;
                    try {
                        if (bleNfcDevice.isAutoSearchCard()) {
                            //如果是自动寻卡的，寻到卡后，先关闭自动寻卡
                            bleNfcDevice.stoptAutoSearchCard();
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //读卡结束，重新打开自动寻卡
                            startAutoSearchCard();

                            //打开蜂鸣器提示读卡完成
                            if (isReadWriteCardSuc) {
                                bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                            }
                            else {
                                bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                            }
                        }
                        else {
//                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //如果不是自动寻卡，读卡结束,关闭天线
//                            bleNfcDevice.closeRf();
                        }

//                        //打开蜂鸣器提示读卡完成
//                        if (isReadWriteCardSuc) {
//                            bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
//                        }
//                        else {
//                            bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
//                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onReceiveRfmSentApduCmd(byte[] bytApduRtnData) {
            super.onReceiveRfmSentApduCmd(bytApduRtnData);

            System.out.println("Activity接收到APDU回调：" + StringTool.byteHexToSting(bytApduRtnData));
        }

        @Override
        public void onReceiveRfmClose(boolean blnIsCloseSuc) {
            super.onReceiveRfmClose(blnIsCloseSuc);
        }

        @Override
        //按键返回回调
        public void onReceiveButtonEnter(byte keyValue) {
            if (keyValue == DeviceManager.BUTTON_VALUE_SHORT_ENTER) { //按键短按
                System.out.println("Activity接收到按键短按回调");
                msgBuffer.append("按键短按\r\n");
                handler.sendEmptyMessage(0);
            }
            else if (keyValue == DeviceManager.BUTTON_VALUE_LONG_ENTER) { //按键长按
                System.out.println("Activity接收到按键长按回调");
                msgBuffer.append("按键长按\r\n");
                handler.sendEmptyMessage(0);
            }
        }
    };

    //搜索按键监听
    private class StartSearchButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED) ) {
                bleNfcDevice.requestDisConnectDevice();
                return;
            }

            mScanner.startScan();
        }
    }

    //读卡按键监听
    private class SendButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            //寻卡一次
            bleNfcDevice.requestRfmSearchCard(ComByteManager.ISO14443_P4, new DeviceManager.onReceiveRfnSearchCardListener() {
                @Override
                public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
                    //在此进行验证密码、读写操作
                    if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                        return;
                    }
                    if (cardType == DeviceManager.CARD_TYPE_MIFARE) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e(TAG, "单次读写 ... ...");
                                boolean isReadWriteCardSuc = writeOrReadMIData2();
                                try {
                                    //如果不是自动寻卡，读卡结束,关闭天线
                                    bleNfcDevice.closeRf();
                                    //打开蜂鸣器提示读卡完成
                                    if (isReadWriteCardSuc) {
                                        bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                                    } else {
                                        bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            });
        }
    }

    //修改蓝牙名称按键监听
    private class changeBleNameButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }

            final EditText inputEditText = new EditText(MainActivity.this);
            //inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
            //inputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("修改蓝牙名称")
                    .setMessage("请输入新名称")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setView(inputEditText)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            final String bleName = inputEditText.getText().toString();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        //开始验证
                                        if (bleNfcDevice.changeBleName(bleName)) {
                                            msgBuffer.delete(0, msgBuffer.length());
                                            msgBuffer.append("蓝牙名称修改成功！重启设备后生效。").append("\r\n");
                                            handler.sendEmptyMessage(0);
                                        }
                                        else {
                                            msgBuffer.delete(0, msgBuffer.length());
                                            msgBuffer.append("蓝牙名称修改失败！").append("\r\n");
                                            handler.sendEmptyMessage(0);
                                        }
                                    } catch (DeviceNoResponseException e) {
                                        e.printStackTrace();
                                        msgBuffer.delete(0, msgBuffer.length());
                                        msgBuffer.append("蓝牙名称修改失败！").append("\r\n");
                                        handler.sendEmptyMessage(0);
                                    }
                                }
                            }).start();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }

    //清空显示按键监听
    private class claerButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            msgBuffer.delete(0, msgBuffer.length());
            handler.sendEmptyMessage(0);
        }
    }

    //打开蜂鸣器监听
    private class OpenBeepButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestOpenBeep(50, 50, 255, new DeviceManager.onReceiveOpenBeepCmdListener() {
                @Override
                public void onReceiveOpenBeepCmd(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("打开蜂鸣器成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //关闭蜂鸣器监听
    private class closeBeepButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestOpenBeep(50, 50, 0, new DeviceManager.onReceiveOpenBeepCmdListener() {
                @Override
                public void onReceiveOpenBeepCmd(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("关闭蜂鸣器成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //打开防丢器功能监听
    private class OpenAntiLostButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestAntiLostSwitch(true, new DeviceManager.onReceiveAntiLostSwitchListener() {
                @Override
                public void onReceiveAntiLostSwitch(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("打开防丢器功能成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //关闭防丢器功能监听
    private class CloseAntiLostButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestAntiLostSwitch(false, new DeviceManager.onReceiveAntiLostSwitchListener() {
                @Override
                public void onReceiveAntiLostSwitch(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("关闭防丢器功能成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //打开自动寻卡按键监听
    private class OpenAutoSearchCardButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //打开/关闭自动寻卡，200ms间隔，寻M1/UL卡
                        boolean isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
                        if (isSuc) {
                            msgBuffer.delete(0, msgBuffer.length());
                            msgBuffer.append("自动寻卡已打开！\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        else {
                            msgBuffer.delete(0, msgBuffer.length());
                            msgBuffer.append("自动寻卡已关闭！\r\n");
                            handler.sendEmptyMessage(0);
                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    //关闭自动寻卡按键监听
    private class CloseAutoSearchCardButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            //打开/关闭自动寻卡，100ms间隔，寻M1/UL卡、CPU卡
            bleNfcDevice.requestRfmAutoSearchCard(false, (byte) 20, ComByteManager.ISO14443_P4, new DeviceManager.onReceiveAutoSearchCardListener() {
                @Override
                public void onReceiveAutoSearchCard(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("自动寻卡已打开！\r\n");
                        handler.sendEmptyMessage(0);
                    }
                    else {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("自动寻卡已关闭！\r\n");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //开始自动寻卡
    private boolean startAutoSearchCard() throws DeviceNoResponseException {
        //打开自动寻卡，200ms间隔，寻M1/UL卡
        boolean isSuc = false;
        int falseCnt = 0;
        do {
            isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
        }while (!isSuc && (falseCnt++ < 10));
        if (!isSuc){
            //msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("不支持自动寻卡！\r\n");
            handler.sendEmptyMessage(0);
        }
        return isSuc;
    }

    //读写卡Demo
    private boolean readWriteCardDemo(int cardType) {
        switch (cardType) {
            case DeviceManager.CARD_TYPE_ISO4443_B:  //寻到 B cpu卡
                final Iso14443bCard iso14443bCard = (Iso14443bCard) bleNfcDevice.getCard();

//                Type4Tag type4Tag = new Type4Tag(iso14443bCard.deviceManager);
//                //读NDEF demo
//                try {
//                    msgBuffer.delete(0, msgBuffer.length());
//                    msgBuffer.append("开始写NDEF\r\n");
//                    handler.sendEmptyMessage(0);
//                    NdefRecord textRecord = Ntag21x.createTextRecord("深圳市德科物联技术有限公司");
//                    NdefMessage writeNdefMessage = new NdefMessage(new NdefRecord[] {textRecord});
//                    System.out.println("writeNdefMessage:" + StringTool.byteHexToSting(writeNdefMessage.toByteArray()));
//                    boolean isSuc = type4Tag.NdefWrite(writeNdefMessage);
//                    if (isSuc) {
//                        msgBuffer.append("写NDEF成功\r\n");
//                    }
//                    else {
//                        msgBuffer.append("写NDEF失败\r\n");
//                    }
//                    handler.sendEmptyMessage(0);
//
//                    msgBuffer.append("开始读NDEF\r\n");
//                    handler.sendEmptyMessage(0);
//                    NdefMessage ndefMessage = type4Tag.NdefRead();
//                    if (ndefMessage != null) {
//                        msgBuffer.append("读NDEF成功：\r\n");
//                        NdefRecord[] ndefRecords = ndefMessage.getRecords();
//                        for (NdefRecord ndefRecord : ndefRecords) {
//                            try {
//                                msgBuffer.append(new String(ndefRecord.getPayload(), "UTF-8")).append("\r\n");
//                            } catch (UnsupportedEncodingException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                    else {
//                        msgBuffer.append("读NDEF失败\r\n");
//                    }
//                    handler.sendEmptyMessage(0);
//                } catch (CardNoResponseException e) {
//                    e.printStackTrace();
//                    msgBuffer.append(e.getMessage() + "\r\n");
//                    handler.sendEmptyMessage(0);
//                }

                if (iso14443bCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到ISO14443-B卡->UID:(身份证发送0036000008指令获取UID)\r\n");
                    handler.sendEmptyMessage(0);
                    //获取身份证UID的指令流
                    final byte[][] sfzCmdBytes = {
                            {0x00, (byte) 0x84, 0x00, 0x00, 0x08},
                            {0x00, 0x36, 0x00, 0x00, 0x08},
                    };
                    System.out.println("发送指令流");
                    for (byte[] aBytes : sfzCmdBytes) {
                        try {
                            msgBuffer.append("发送：").append(StringTool.byteHexToSting(aBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                            byte returnBytes[] = iso14443bCard.transceive(aBytes);
                            msgBuffer.append("返回：").append(StringTool.byteHexToSting(returnBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                        } catch (CardNoResponseException e) {
                            e.printStackTrace();
                            return false;
                        }
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO4443_A:   //寻到A CPU卡
                final CpuCard cpuCard = (CpuCard) bleNfcDevice.getCard();
                if (cpuCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到CPU卡->UID:").append(cpuCard.uidToString()).append("\r\n");
                    handler.sendEmptyMessage(0);
                    try{
                        //选择深圳通主文件
                        byte[] bytApduRtnData = cpuCard.transceive(SZTCard.getSelectMainFileCmdByte());
                        if (bytApduRtnData.length <= 2) {
                            System.out.println("不是深圳通卡，当成银行卡处理！");
                            //选择储蓄卡交易文件
                            String cpuCardType;
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDepositCardPayFileCmdBytes());
                            if (bytApduRtnData.length <= 2) {
                                System.out.println("不是储蓄卡，当成借记卡处理！");
                                //选择借记卡交易文件
                                bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDebitCardPayFileCmdBytes());
                                if (bytApduRtnData.length <= 2) {
                                    msgBuffer.append("未知CPU卡！");
                                    handler.sendEmptyMessage(0);
                                    return false;
                                }
                                else {
                                    cpuCardType = "储蓄卡";
                                }
                            }
                            else {
                                cpuCardType = "借记卡";
                            }

                            //读取银行卡卡号
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getCardNumberCmdBytes());

                            //提取银行卡卡号
                            String cardNumberString = FinancialCard.extractCardNumberFromeRturnBytes(bytApduRtnData);
                            if (cardNumberString == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                return false;
                            }

                            msgBuffer.append(cpuCardType + "卡号：" + cardNumberString);
                            handler.sendEmptyMessage(0);

                            //读交易记录
                            System.out.println("发送APDU指令-读10条交易记录");
                            for (int i = 1; i <= 10; i++) {
                                bytApduRtnData = cpuCard.transceive(FinancialCard.getTradingRecordCmdBytes((byte) i));
                                msgBuffer.append(FinancialCard.extractTradingRecordFromeRturnBytes(bytApduRtnData));
                                handler.sendEmptyMessage(0);
                            }
                        }
                        else {  //深圳通处理流程
                            bytApduRtnData = cpuCard.transceive(SZTCard.getBalanceCmdByte());
                            if (SZTCard.getBalance(bytApduRtnData) == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                System.out.println("未知CPU卡！");
                                return false;
                            }
                            else {
                                msgBuffer.append("深圳通余额：").append(SZTCard.getBalance(bytApduRtnData));
                                handler.sendEmptyMessage(0);
                                System.out.println("余额：" + SZTCard.getBalance(bytApduRtnData));
                                //读交易记录
                                System.out.println("发送APDU指令-读10条交易记录");
                                for (int i = 1; i <= 10; i++) {
                                    bytApduRtnData = cpuCard.transceive(SZTCard.getTradeCmdByte((byte) i));
                                    msgBuffer.append("\r\n").append(SZTCard.getTrade(bytApduRtnData));
                                    handler.sendEmptyMessage(0);
                                }
                            }
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_FELICA:  //寻到FeliCa
                FeliCa feliCa = (FeliCa) bleNfcDevice.getCard();
                if (feliCa != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("读取服务008b中数据块0000的数据：\r\n");
                    handler.sendEmptyMessage(0);
                    byte[] pServiceList = {(byte) 0x8b, 0x00};
                    byte[] pBlockList = {0x00, 0x00, 0x00};
                    try {
                        byte[] pBlockData = feliCa.read((byte) 1, pServiceList, (byte) 1, pBlockList);
                        msgBuffer.append(StringTool.byteHexToSting(pBlockData)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ULTRALIGHT: //寻到Ultralight卡
                String writeText = System.currentTimeMillis() + "深圳市德科物联技术有限公司，专业非接触式智能卡读写器方案商！深圳市德科物联技术有限公司，专业非接触式智能卡读写器方案商！";
                if (msgText.getText().toString().length() > 0) {
                    writeText = msgText.getText().toString();
                }

                msgBuffer.delete(0, msgBuffer.length());

                final Ntag21x ntag21x = (Ntag21x) bleNfcDevice.getCard();
                if (ntag21x != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到Ultralight卡 ->UID:").append(ntag21x.uidToString()).append("\r\n");
                    handler.sendEmptyMessage(0);
                    try {
                        //写NDEF demo
                        msgBuffer.append("\r\n开始写NDEF\r\n");
                        handler.sendEmptyMessage(0);
                        NdefRecord textRecord = null;
//                        try {
                        textRecord = Ntag21x.createTextRecord(writeText);
                        //new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[] {}, ("zh" + writeText).getBytes("UTF-8"));
//                        } catch (UnsupportedEncodingException e) {
//                            e.printStackTrace();
//                        }
                        NdefMessage writeNdefMessage = new NdefMessage(new NdefRecord[] {textRecord});
                        boolean isSuc = ntag21x.NdefWrite(writeNdefMessage);
                        if (isSuc) {
                            msgBuffer.append("写NDEF成功\r\n");
                        }
                        else {
                            msgBuffer.append("写NDEF失败\r\n");
                        }
                        handler.sendEmptyMessage(0);

                        //读NDEF demo
                        msgBuffer.append("\r\n开始读NDEF\r\n");
                        handler.sendEmptyMessage(0);
                        NdefMessage ndefMessage = ntag21x.NdefRead();
                        if (ndefMessage != null) {
                            msgBuffer.append("读NDEF成功：\r\n");
                            NdefRecord[] ndefRecords = ndefMessage.getRecords();
                            for (NdefRecord ndefRecord : ndefRecords) {
                                try {
                                    msgBuffer.append(new String(ndefRecord.getPayload(), "UTF-8")).append("\r\n");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        else {
                            msgBuffer.append("读NDEF失败\r\n");
                        }
                        handler.sendEmptyMessage(0);

//                        //读写单个块Demo
//                        msgBuffer.append("开始读取块0数据：\r\n");
//                        handler.sendEmptyMessage(0);
//                        byte[] readTempBytes = ntag21x.read((byte) 0);
//                        msgBuffer.append("返回：").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
//                        handler.sendEmptyMessage(0);

//                        //读写文本Demo，不带进度回调
//                        msgBuffer.append("开始写入文本：\r\n");
//                        handler.sendEmptyMessage(0);
//                        boolean isSuc = ntag21x.NdefTextWrite(writeText);
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            msgBuffer.append("开始读取文本").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            String text = ntag21x.NdefTextRead();
//                            msgBuffer.append("读取成功：\r\n").append(text).append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        else {
//                            msgBuffer.append("写文本失败！").append("\r\n");
//                            showReadWriteDialog("正在读取数据", 0);
//                        }

                        //读写文本Demo，带进度回调
//                        msgBuffer.append("开始写入文本：\r\n");
//                        showReadWriteDialog("正在写入文本", 1);
//                        showReadWriteDialog("正在写入文本", 1);
//                        boolean isSuc = ntag21x.NdefTextWriteWithScheduleCallback(writeText, new Ntag21x.onReceiveScheduleListener() {
//                            @Override
//                            public void onReceiveSchedule(int rate) {
//                                //显示进度，写入过程会不断回调到此
//                                showReadWriteDialog("正在写入文本", rate);
//                            }
//                        });
//
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            msgBuffer.append("开始读取文本").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            String text = ntag21x.NdefTextReadWithScheduleCallback(new Ntag21x.onReceiveScheduleListener() {
//                                @Override
//                                public void onReceiveSchedule(int rate) {
//                                    showReadWriteDialog("正在读取数据", rate);
//                                }
//                            });
//                            msgBuffer.append("读取成功：\r\n").append(text).append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        else {
//                            msgBuffer.append("写文本失败！").append("\r\n");
//                            showReadWriteDialog("正在读取数据", 0);
//                        }

//                        //任意长度读写Demo,不带进度回调方式
//                        byte[] writeBytes = new byte[888];
//                        Arrays.fill(writeBytes, (byte) 0xAA);
//                        msgBuffer.append("开始写888个字节数据：0x30").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        boolean isSuc = ntag21x.longWrite((byte) 4, writeBytes);
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            msgBuffer.append("开始读888个字节数据").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            readTempBytes = ntag21x.longRead((byte) 4, (byte) (888 / 4));
//                            msgBuffer.append("读取成功：\r\n").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        else {
//                            msgBuffer.append("写数据失败！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }

//                        //任意长度读写Demo，带进度回调
//                        showReadWriteDialog("正在写入数据", 1);
//                        showReadWriteDialog("正在写入数据", 1);
//                        byte[] writeBytes = new byte[888];
//                        Arrays.fill(writeBytes, (byte) 0x30);
//                        msgBuffer.append("开始写888个字节数据：0x30").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        boolean isSuc = ntag21x.longWriteWithScheduleCallback((byte) 4, writeBytes, new Ntag21x.onReceiveScheduleListener() {
//                            @Override
//                            public void onReceiveSchedule(int rate) {
//                                showReadWriteDialog("正在写入数据", rate);
//                            }
//                        });
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            msgBuffer.append("开始读888个字节数据").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                            readTempBytes = ntag21x.longReadWithScheduleCallback((byte) 4, (byte) (888 / 4), new Ntag21x.onReceiveScheduleListener() {
//                                @Override
//                                public void onReceiveSchedule(int rate) {
//                                    showReadWriteDialog("正在读取数据", rate);
//                                }
//                            });
//                            msgBuffer.append("读取成功：\r\n").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
//                            showReadWriteDialog("正在读取数据", 100);
//                        }
//                        else {
//                            msgBuffer.append("写数据失败！").append("\r\n");
//                            showReadWriteDialog("正在读取数据", 0);
//                        }


//                        msgBuffer.append("开始读100个字节数据").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        readTempBytes = ntag21x.longReadWithScheduleCallback((byte) 4, (byte) (100 / 4), new Ntag21x.onReceiveScheduleListener() {
//                            @Override
//                            public void onReceiveSchedule(int rate) {
//                                showReadWriteDialog("正在读取数据", rate);
//                            }
//                        });
//                        msgBuffer.append("读取成功：\r\n").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
//                        showReadWriteDialog("正在读取数据", 100);

                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        msgBuffer.append(e.getMessage()).append("\r\n");
                        showReadWriteDialog("正在写入数据", 0);
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_MIFARE:   //寻到Mifare卡
                Log.e(TAG, "自动读写 ... ...");
                writeOrReadMIData2();
                break;
//                final Mifare mifare = (Mifare) bleNfcDevice.getCard();
//                if (mifare != null) {
//                    msgBuffer.delete(0, msgBuffer.length());
//                    msgBuffer.append("寻到Mifare卡->UID:").append(mifare.uidToString()).append("\r\n");
//                    msgBuffer.append("开始验证第3块密码\r\n");
//                    handler.sendEmptyMessage(0);
//                    byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
//                    int i = 0;
//                    boolean anth = false;
//                    for (i=0; i<64; i++) {
//                        try {
//                            if (i % 4 == 0) {
//                                anth = mifare.authenticate((byte) i, Mifare.MIFARE_KEY_TYPE_A, key);
//                            }
//                            if (anth) {
//                                handler.sendEmptyMessage(0);
//                                byte[] readDataBytes = mifare.read((byte) i);
//                                msgBuffer.append("块" + i + "数据:\r\n").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
//                                handler.sendEmptyMessage(0);
//                            } else {
//                                msgBuffer.append("验证密码失败\r\n");
//                                handler.sendEmptyMessage(0);
//                                return false;
//                            }
//                        } catch (CardNoResponseException e) {
//                            e.printStackTrace();
//                            return false;
//                        }
//                    }
//                }
//                break;

//                final Mifare mifare = (Mifare) bleNfcDevice.getCard();
//                if (mifare != null) {
//                    msgBuffer.delete(0, msgBuffer.length());
//                    msgBuffer.append("寻到Mifare卡->UID:").append(mifare.uidToString()).append("\r\n");
//                    msgBuffer.append("开始验证第1块密码\r\n");
//                    handler.sendEmptyMessage(0);
//                    byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
//                    try {
//                        boolean anth = mifare.authenticate((byte) 0x01, Mifare.MIFARE_KEY_TYPE_A, key);
//                        if (anth) {
//                            msgBuffer.append("验证密码成功\r\n");
//                            msgBuffer.append("写11223344556677889900112233445566到块1\r\n");
//                            handler.sendEmptyMessage(0);
//                            boolean isSuc = mifare.write((byte)1, new byte[]{(byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66,
//                                    (byte)0x77, (byte)0x88, (byte)0x99, (byte) 0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66});
//
//                            if (isSuc) {
//                                msgBuffer.append("写成功！\r\n");
//                                msgBuffer.append("读块1数据\r\n");
//                                handler.sendEmptyMessage(0);
//                                byte[] readDataBytes = mifare.read((byte) 1);
//                                msgBuffer.append("块1数据:").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
//                                handler.sendEmptyMessage(0);
//                            } else {
//                                msgBuffer.append("写失败！\r\n");
//                                handler.sendEmptyMessage(0);
//                                return false;
//                            }
//                        }
//                        else {
//                            msgBuffer.append("验证密码失败\r\n");
//                            handler.sendEmptyMessage(0);
//                            return false;
//                        }
//                    } catch (CardNoResponseException e) {
//                        e.printStackTrace();
//                        return false;
//                    }
//                }
//                break;
            case DeviceManager.CARD_TYPE_ISO15693: //寻到15693卡
                final Iso15693Card iso15693Card = (Iso15693Card) bleNfcDevice.getCard();
                if (iso15693Card != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到15693卡->UID:").append(iso15693Card.uidToString()).append("\r\n");
//                    msgBuffer.append("读块0数据\r\n");
//                    handler.sendEmptyMessage(0);
                    try {
//                        byte[] cmdBytes = new byte[11];
//                        cmdBytes[0] = 0x22;
//                        cmdBytes[1] = 0x20;
//                        System.arraycopy(iso15693Card.uid, 0, cmdBytes, 2, 8);
//                        cmdBytes[10] = 0x01;
//
//                        msgBuffer.append("指令透传发送：" + StringTool.byteHexToSting(cmdBytes) + "\r\n");
//                        handler.sendEmptyMessage(0);
//                        byte[] returnBytes = iso15693Card.transceive(cmdBytes);
//                        msgBuffer.append("返回：" + StringTool.byteHexToSting(returnBytes)).append("\r\n");
//
//                        //读写单个块Demo
//                        msgBuffer.append("写数据01020304到块4").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        boolean isSuc = iso15693Card.write((byte)4, new byte[] {0x01, 0x02, 0x03, 0x04});
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        else {
//                            msgBuffer.append("写数据失败！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        msgBuffer.append("读块4数据").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        byte[] bytes = iso15693Card.read((byte) 4);
//                        msgBuffer.append("块4数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
//                        handler.sendEmptyMessage(0);
//
//                        //读写多个块Demo
//                        msgBuffer.append("写数据0102030405060708到块5、6").append("\r\n");
//                        handler.sendEmptyMessage(0);
//                        isSuc = iso15693Card.writeMultiple((byte)5, (byte)2, new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
//                        if (isSuc) {
//                            msgBuffer.append("写数据成功！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }
//                        else {
//                            msgBuffer.append("写数据失败！").append("\r\n");
//                            handler.sendEmptyMessage(0);
//                        }

                        msgBuffer.append("读块0~14数据").append("\r\n");
                        handler.sendEmptyMessage(0);
                        byte[] bytes = iso15693Card.ReadMultiple((byte) 0, (byte)15);
                        msgBuffer.append("块0~14数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
        }
        return true;
    }

    //发送读写进度条显示Handler
    private void showReadWriteDialog(String msg, int rate) {
        Message message = new Message();
        message.what = 4;
        message.arg1 = rate;
        message.obj = msg;
        handler.sendMessage(message);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            msgText.setText(msgBuffer);

            if ( (bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED) || ((bleNfcDevice.isConnection() == BleManager.STATE_CONNECTING)) ) {
                searchButton.setText("断开连接");
            }
            else {
                searchButton.setText("搜索设备");
            }

            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;

                case 4:   //读写进度条
                    if ((msg.arg1 == 0) || (msg.arg1 == 100)) {
                        readWriteDialog.dismiss();
                        readWriteDialog.setProgress(0);
                    } else {
                        readWriteDialog.setMessage((String) msg.obj);
                        readWriteDialog.setProgress(msg.arg1);
                        if (!readWriteDialog.isShowing()) {
                            readWriteDialog.show();
                        }
                    }
                    break;
                case 5:
                    msgText.setText("");
                    break;
            }
        }
    };

    /**
     * 浮点体温数据转换BCD
     * @param temp
     * @return
     */
    private byte[] tempToBCB(float temp) {
        byte[] bcd = new byte[2];
        int temp1 = (int)temp;
        bcd[0] = (byte)(temp1/10*16+temp1%10);
        int temp2 = (int)((temp - temp1) * 100);
        bcd[1] = (byte)(temp2/10*16+temp2%10);
        return bcd;
    }

    /**
     * BCD码体温转换浮点
     * @param bcd
     * @return
     */
    private float tempFromBCD(byte[] bcd) {
        if (bcd.length != 2) {
            return -1f;
        }

        StringBuffer temp = new StringBuffer(bcd.length * 2);
        temp.append((byte) ((bcd[0] & 0xf0) >>> 4));
        temp.append((byte) (bcd[0] & 0x0f));
        temp.append(".");
        temp.append((byte) ((bcd[1] & 0xf0) >>> 4));
        temp.append((byte) (bcd[1] & 0x0f));
        try {
            return Float.parseFloat(temp.toString());
        } catch (Exception e) {

        }
        return -1f;
    }

    /**
     * 构建数据块
     * @param num
     * @return
     */
    private byte[] genBlock(int num) {
        byte[] datas = new byte[16];
        if (num == 0) {
            int index = 0;
            // 写入mac
            datas[index++] = 0x11;
            datas[index++] = 0x22;
            datas[index++] = 0x33;
            datas[index++] = 0x44;
            datas[index++] = 0x55;
            datas[index++] = 0x66;
            // 写入时间戳
            long curTime = System.currentTimeMillis();
            datas[index++] = (byte)((curTime >> (7*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (6*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (5*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (4*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (3*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (2*8)) & 0xFF);
            datas[index++] = (byte)((curTime >> (1*8)) & 0xFF);
            datas[index++] = (byte)(curTime & 0xFF);
        } else if (num == 1) {
            // 写入生命体征
            int hr = Integer.parseInt(etHr.getText().toString());
            int rr = Integer.parseInt(etRr.getText().toString());
            int spo2 = Integer.parseInt(etSpO2.getText().toString());
            int pr = Integer.parseInt(etPr.getText().toString());
            int pi = (int)(Float.parseFloat(etPi.getText().toString()) * 100);
            float temp = Float.parseFloat(etTemp.getText().toString());
            int sbp = Integer.parseInt(etSbp.getText().toString());
            int dbp = Integer.parseInt(etDbp.getText().toString());
            int mbp = Integer.parseInt(etMbp.getText().toString());
            int index = 0;
            datas[index++] = (byte)spo2;
            datas[index++] = (byte)(pi >> 8 & 0xFF);
            datas[index++] = (byte)(pi & 0xFF);
            datas[index++] = (byte)(pr >> 8 & 0xFF);
            datas[index++] = (byte)(pr & 0xFF);
            datas[index++] = (byte)(hr >> 8 & 0xFF);
            datas[index++] = (byte)(hr & 0xFF);
            datas[index++] = (byte)rr;
            byte[] tempArr = tempToBCB(temp);
            datas[index++] = tempArr[0];
            datas[index++] = tempArr[1];
            datas[index++] = (byte)(sbp >> 8 & 0xFF);
            datas[index++] = (byte)(sbp & 0xFF);
            datas[index++] = (byte)(dbp >> 8 & 0xFF);
            datas[index++] = (byte)(dbp & 0xFF);
            datas[index++] = (byte)(mbp >> 8 & 0xFF);
            datas[index++] = (byte)(mbp & 0xFF);        }
        return datas;
    }

    public void writeOrReadMIData2(final int mode) {
        if ( (bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED) ) {
            msgText.setText("设备未连接，请先连接设备！");
            return;
        }
        //寻卡一次
        bleNfcDevice.requestRfmSearchCard(ComByteManager.ISO14443_P4, new DeviceManager.onReceiveRfnSearchCardListener() {
            @Override
            public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
                //在此进行验证密码、读写操作
                if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                    Log.e(TAG, "识别错误： blnIsSus is " + blnIsSus + ", cardType is " + cardType);
                    return;
                }
                if (cardType == DeviceManager.CARD_TYPE_MIFARE) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG, "单次读写 ... ...");
                            boolean isReadWriteCardSuc = false;
                                    if (mode == 0) {
                                        isReadWriteCardSuc = wismedWrite();
                                    }else if (mode == 1) {
                                        isReadWriteCardSuc = wismedRead();
                                    }
                            try {
                                //如果不是自动寻卡，读卡结束,关闭天线
                                bleNfcDevice.closeRf();
                                //打开蜂鸣器提示读卡完成
                                if (isReadWriteCardSuc) {
                                    bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                                } else {
                                    bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });
    }

    /**
     * 为麦单次写
     * @return
     */
    private boolean wismedWrite() {
        Log.e(TAG, "wismed 写入数据 ... ...");
        final Mifare mifare = (Mifare) bleNfcDevice.getCard();
        if (mifare != null) {
            Log.e(TAG, "寻到Mifare卡->UID:" + mifare.uidToString() + "\r\n");
            int [] blockArr = new int[] {4,5};
            for (int i = 0; i < blockArr.length; i++) {
                Log.e(TAG,"开始验证第"+blockArr[i]+"块密码\r\n");
                byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
                try {
                    boolean anth = mifare.authenticate((byte) blockArr[i], Mifare.MIFARE_KEY_TYPE_A, key);
                    if (anth) {
                        Log.e(TAG,"验证密码成功\r\n");
                        byte[] datas = new byte[16];
                        if (blockArr[i] == 4) {
                            Log.e(TAG,"写Mac地址和时间戳到块"+blockArr[i]+"\r\n");
                            datas = genBlock(0);
                        } else if (blockArr[i] == 5) {
                            Log.e(TAG,"写生命体征到块"+blockArr[i]+"\r\n");
                            datas = genBlock(1);
                        }
//                        datas = new byte[]{(byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66,
//                                (byte)0x77, (byte)0x88, (byte)0x99, (byte) 0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66};
                        boolean isSuc = mifare.write((byte) blockArr[i], datas);
                        if (isSuc) {
                            Log.e(TAG,"写块"+blockArr[i]+"成功！\r\n");
//                            msgBuffer.append("读块"+blockArr[i]+"数据\r\n");
//                            byte[] readDataBytes = mifare.read((byte)blockArr[i]);
//                            msgBuffer.append("块1数据:").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
//                            handler.sendEmptyMessage(0);
                        } else {
                            Log.e(TAG,"写失败！\r\n");
                        }
                    } else {
                        Log.e(TAG,"验证密码块"+blockArr[i]+"失败\r\n");
                    }
                } catch (CardNoResponseException e) {
                    e.printStackTrace();
                }
                Log.e(TAG,"操作结束!!!\r\n");
            }
        } else {
            Log.e(TAG,"没有寻到Mifare卡!!!\r\n");
        }
        return true;
    }

    /**
     * 为麦单次读
     * @return
     */
    private boolean wismedRead() {
        Log.e(TAG, "wismed 写入数据 ... ...");
        final Mifare mifare = (Mifare) bleNfcDevice.getCard();
        if (mifare != null) {
            Log.e(TAG, "寻到Mifare卡->UID:" + mifare.uidToString() + "\r\n" + "开始验证第3块密码\r\n");
            byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
            boolean anth = false;
            for (int i=4; i<8; i++) {
                try {
                    if (i % 4 == 0) {
                        anth = mifare.authenticate((byte) i, Mifare.MIFARE_KEY_TYPE_A, key);
                    }
                    if (anth) {
                        byte[] readDataBytes = mifare.read((byte) i);
                        Log.e(TAG, "块" + i + "数据:\r\n" + StringTool.byteHexToSting(readDataBytes) + "\r\n");
                    } else {
                        Log.e(TAG,"验证密码失败\r\n");
                    }
                } catch (CardNoResponseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.e(TAG,"没有寻到Mifare卡!!!\r\n");
        }
        return true;
    }

    private String TAG = "wismed";
    private boolean writeOrReadMIData2() {
        wismedWrite();
        wismedRead();
        // todo调试自动读写
        if (1==1)
            return true;

        final Mifare mifare = (Mifare) bleNfcDevice.getCard();
        if (mifare != null) {
            Log.e(TAG, "寻到Mifare卡->UID:" + mifare.uidToString() + "\r\n" + "开始验证第3块密码\r\n");
            byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
            int i = 0;
            boolean anth = false;
            for (i=0; i<64; i++) {
                try {
                    if (i % 4 == 0) {
                        anth = mifare.authenticate((byte) i, Mifare.MIFARE_KEY_TYPE_A, key);
                    }
                    if (anth) {
                        byte[] readDataBytes = mifare.read((byte) i);
                        Log.e(TAG, "块" + i + "数据:\r\n" + StringTool.byteHexToSting(readDataBytes) + "\r\n");
                    } else {
                        Log.e(TAG,"验证密码失败\r\n");
                    }
                } catch (CardNoResponseException e) {
                    e.printStackTrace();
                }
            }
        }

        if (mifare != null) {
            Log.e(TAG, "寻到Mifare卡->UID:" + mifare.uidToString() + "\r\n" + "开始验证第1块密码\r\n");
            byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
            try {
                boolean anth = mifare.authenticate((byte) 0x04, Mifare.MIFARE_KEY_TYPE_A, key);
                if (anth) {
                    Log.e(TAG, "验证密码成功\r\n" + "写11223344556677889900112233445566到块1\r\n");
                    boolean isSuc = mifare.write((byte)4, new byte[]{(byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66,
                            (byte)0x77, (byte)0x88, (byte)0x99, (byte) 0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66});

                    if (isSuc) {
                        Log.e(TAG, "写成功！\r\n" + "读块4数据\r\n");
                        byte[] readDataBytes = mifare.read((byte) 4);
                        Log.e(TAG, "块4数据:" + StringTool.byteHexToSting(readDataBytes));
                    } else {
                        Log.e(TAG, "写失败！\r\n");
                    }
                }
                else {
                    Log.e(TAG, "验证密码失败\r\n");
                }
                anth = mifare.authenticate((byte) 0x05, Mifare.MIFARE_KEY_TYPE_A, key);
                if (anth) {
                    Log.e(TAG, "验证密码成功\r\n" + "写11223344556677889900112233445566到块1\r\n");
                    boolean isSuc = mifare.write((byte)5, new byte[]{(byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66,
                            (byte)0x77, (byte)0x88, (byte)0x99, (byte) 0x00, (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66});

                    if (isSuc) {
                        Log.e(TAG, "写成功！\r\n" + "读块5数据\r\n");
                        byte[] readDataBytes = mifare.read((byte)5);
                        Log.e(TAG, "块5数据:" + StringTool.byteHexToSting(readDataBytes));
                    } else {
                        Log.e(TAG, "写失败！\r\n");
                    }
                }
                else {
                    Log.e(TAG, "验证密码失败\r\n");
                }
            } catch (CardNoResponseException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
